package com.easylinkin.sm.context;

import static site.morn.framework.context.CommonConstant.Caches.ACTIVE_DEPARTMENT;
import static site.morn.framework.context.CommonConstant.Caches.DEPARTMENT;

import com.easylinkin.sm.entity.Department;
import com.easylinkin.sm.entity.User;
import com.easylinkin.sm.service.DepartmentService;

import java.util.Objects;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import site.morn.bean.annotation.Target;
import site.morn.cache.CacheGroup;
import site.morn.framework.context.AccountContext;
import site.morn.framework.context.DepartmentContextProducer;

/**
 * 获取组织机构
 *
 * @author TianGanLin
 * @since 0.1.1, 2019/5/21
 */
@Slf4j
@Component
@Target(Department.class)
public class SmDepartmentContextProducer implements DepartmentContextProducer<Department> {

  @Resource
  private DepartmentService departmentService;

  @Override
  public Department getActive() {
    String username = AccountContext.currentUsername();
    CacheGroup cacheGroup = AccountContext.cacheGroup();
    return cacheGroup.get(ACTIVE_DEPARTMENT, username, this::getCurrent);
  }

  @Override
  public Department getCurrent() {
    User user = AccountContext.currentUser();
    if (Objects.isNull(user)) {
      return null;
    }
    CacheGroup cacheGroup = AccountContext.cacheGroup();
    return cacheGroup.get(DEPARTMENT, user.getUsername(), () -> get(user.getDepartmentId()));
  }

  @Override
  public Department get(Long id) {
    Department department = departmentService.get(id);
    if (Objects.isNull(department)) {
      log.error("组织机构不存在[id={}]", id);
      return null;
    }
    return department;
  }
}
